#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>

int _system(char *p, int iswait)
{
	printf("start execl [%s]\n", p);
	pid_t child_pid;

	child_pid = vfork();
	if (child_pid < 0)
	{
		printf( "vfork fail! strerr = [%s]\n", strerror(errno));
		return -1;
	}

	if (child_pid == 0)
	{
		if(iswait == 0) { // 通过两次调用fork, 避免产生Zombie进程, 孙进程由init进程接管回收
			pid_t grandson_pid = vfork();
			if(grandson_pid==0) {
				execl("/bin/sh", "sh", "-c", p, (char *)0);
				exit(0);
			} else {
				printf("Grandson Pid = %d\n", grandson_pid);
			}
		} else {
			execl("/bin/sh", "sh", "-c", p, (char *)0);
		}
		exit(0);
	}
	else if (child_pid > 0)
	{
		printf("Child Pid = %d\n",child_pid);
	}

	int status = 0;
	do
	{
		if (waitpid(child_pid, &status, 0) == -1)
		{
			perror("waitpid");
			return -1;
		}
	} while (!WIFEXITED(status) && !WIFSIGNALED(status));

	return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

int main(int argc, char *argv[])
{
	int ret = 0;

	//ret = _system("echo test grandson!", 0);
	ret = _system("killall /app/scripts/wlan_ctrl.sh; /app/scripts/wlan_ctrl.sh connect2 wlan0 rtl8192eu 1", 0);
	printf("_system ret = %d\n", ret);
	return ret;
}

